import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex);

import * as api from "../api"
import router from "../router";
import allRoutes from "../router/allRoutes"
import dynamicRoutes from "../router/dynamicRoutes"
import recursionRoutes from "../utils/recursionRoutes"
let userInfo = localStorage.getItem("xdw-userInfo") || "{}"
export default new Vuex.Store({
    state: {
        userInfo:JSON.parse(userInfo), //用户信息
        userRoutes:[], //侧边栏菜单
        breadCrumb:[] //面包屑
    },
    mutations: {  
        // 保存用户信息
        SET_USER_INFO(state,payload) { //设置用户信息
            state.userInfo = payload;
            
        },
        SET_MENULIST(state,payload) { //设置菜单
            state.userRoutes =  payload;
            // console.log(state.userRoutes);
            // 将用户路由动态的添加到routes的配置routes中
            // 将用户路由添加到dynamicRoutes中的 "/" 路径那个配置属性
            let target = dynamicRoutes.find(item=>item.path === "/")
            // console.log(target);
            target.children = payload;
            // 要将用户路由动态的添加到我们的项目之中
            // console.log(dynamicRoutes);
            // 核心方法就是router.addRoutes([])
            // router.addRoutes(dynamicRoutes)
            dynamicRoutes.forEach(item => {
                router.addRoute(item)
            })
        },
        SET_BREADCRUMB(state,payload) {
            state.breadCrumb = payload;
        }

    },
    getters: {

    },
    actions: {
      async  GET_MENULIST({commit}) {
            // 用于获取服务器中当前用户菜单
            let res = await api.getMenulistApi()
            let { menuList } = res.data;
            // console.log(menuList);
            // 使用recursionRoutes方法,计算出用户的路由,提交给mutation
            let userRoutes = recursionRoutes(menuList,allRoutes)
            commit("SET_MENULIST",userRoutes)
        }
    }
})